<template>
  <el-card v-loading="loading" shadow="never" class="common-biz-page">
    <template #header>{{ props.name }}</template>
    <div class="search-form">
      <dymic-form
        ref="searchELe"
        v-model="filterData"
        v-bind="config.filter"
        @onEvent="handleClick"
      />
    </div>
    <div class="form-btns">
      <template v-for="btn in props.actions">
        <el-button v-if="btn.position === '2'" v-bind="btn" @click="canvatAction(btn)">
          {{ btn.label }}
        </el-button>
      </template>
    </div>
    <el-table
      border
      :data="tableData"
      style="margin-bottom: 20px"
      :height="tableHeight"
      @selection-change="e => (selection = e)"
    >
      <el-table-column v-for="column in config.table.columns" v-bind="column">
        <template v-if="column.prop === 'operation'" #default="scope">
          <el-button link v-for="btn in column.buttons" @click="handleClick(btn.event, scope)">
            {{ btn.text }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column fixed="right" v-if="config.table.operater" v-bind="config.table.operater">
        <template #default="scope">
          <template v-for="btn in props.actions">
            <el-button v-if="btn.position === '1'" v-bind="btn" @click="canvatAction(btn, scope)">
              {{ btn.label }}
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex; justify-content: end">
      <el-pagination
        v-model:page-size="params.pageSize"
        v-model:current-page="params.pageNo"
        v-bind="pagination"
      />
    </div>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      :close-on-click-modal="false"
    >
      <dymic-form
        ref="formELe"
        v-model="formData"
        v-bind="config.form"
        @handleClick="handleClick"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button @click="dialog.visible = false">重置</el-button>
          <el-button type="primary" @click="dialog.visible = false">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import request from '../utils/request';
import DymicForm from './DymicForm.vue';
import { ref, reactive, watch, computed, onMounted } from 'vue';

const tableData = ref([]);
const loading = ref(false);

const pagination = ref({
  total: 0,
  background: true,
  layout: 'prev, pager, next, sizes, total',
  pageSizes: [10, 20, 30, 40]
});

const props = defineProps<{
  name: string;
  api: any;
  fields: any[];
  pagination?: any;
  actions?: any;
  tableConfig?: any;
  tableOperater?: any;
  formConfig?: any;
}>();
const filterData = ref({});
const formData = ref({});
const selection = ref([]);

const params = reactive({ pageNo: 1, pageSize: 10 });
const pageInfo = reactive({ height: 0, headHight: 0, footHeight: 0, btnsHeight: 0 });
const dialog = reactive({
  visible: false,
  width: '700px',
  title: '编辑信息'
});

const config = ref(createConfg());
watch(params, (newval, oldval) => {
  if (newval.pageSize !== oldval.pageSize) params.pageNo = 1;
  queryList();
});
watch(
  () => props.fields,
  () => {
    config.value = createConfg();
  }
);
const handleSearch = () => {
  params.pageNo = 1;
  queryList();
};
let lastTime = new Date().getTime();
const resizeObserver = new ResizeObserver(entries => {
  if (new Date().getTime() - lastTime < 100) return;
  pageInfo.headHight = document.querySelector('.search-form')?.clientHeight ?? 0;
  pageInfo.btnsHeight = document.querySelector('.form-btns')?.clientHeight ?? 0;
  lastTime = new Date().getTime();
});
onMounted(() => {
  pageInfo.height = document.querySelector('.menu-layout-body')?.clientHeight ?? 0;
  pageInfo.headHight = document.querySelector('.search-form')?.clientHeight ?? 0;
  pageInfo.btnsHeight = document.querySelector('.form-btns')?.clientHeight ?? 0;
  const searchFormEle = document.querySelector('.search-form');
  if (searchFormEle) resizeObserver.observe(searchFormEle);
});
const tableHeight = computed(() => {
  const { headHight, btnsHeight, height } = pageInfo;
  return height - (btnsHeight + headHight + 160) + 'px';
});

const handleReset = () => {
  // filterFormELe.value?.resetForm();
};
const deleteRow = scope => {
  console.log('deleteRow', scope);
};
const viewDetail = scope => {
  console.log('viewDetail', scope);
};
const editRow = scope => {
  console.log('editRow', scope);
};
const handleClick = (functionName, scope) => {
  const actions = {
    editRow,
    deleteRow,
    viewDetail,
    handleReset,
    handleSearch
  };
  try {
    actions[functionName](scope);
  } catch (error) {
    console.log('错误信息：', error);
  }
};
const canvatAction = (data, scope?) => {
  new Function('data', data.action).bind({
    filterData,
    formData,
    tableData,
    dialog,
    queryList,
    request,
    selection
  })(scope);
};
const queryList = async () => {
  console.log('queryUserList', filterData.value);
  loading.value = true;
  const api = props.api.find(i => i.name === 'query');
  const res = await request[api.method](api.url, { ...params, ...filterData.value });
  pagination.value.total = res.total;
  tableData.value = res.data;
  loading.value = false;
};
queryList();
function createConfg() {
  const { fields, tableConfig, tableOperater, formConfig } = props;
  return {
    form: {
      ...formConfig,
      fields: fields.filter(({ form = false }) => form).map(formItem)
    },
    filter: {
      inline: true,
      actions: [
        { type: 'primary', label: '重置', event: 'handleReset' },
        { type: 'primary', label: '查询', event: 'handleSearch' }
      ],
      fields: fields.filter(({ filter = false }) => filter).map(filterItem)
    },
    table: {
      ...tableConfig,
      columns: fields.filter(({ table = true }) => table),
      operater: tableOperater ? { width: 200, fixed: 'right', label: '操作', ...tableOperater } : {}
    }
  };
}
function filterItem(item) {
  return {
    field: item.prop,
    label: item.label,
    width: 300,
    component: item.filterProps.type,
    options: item.options,
    props: item.filterProps
  };
}
function formItem(item) {
  return {
    field: item.prop,
    label: item.label,
    component: item.formType || 'input',
    options: item.options,
    props: item.props
  };
}
</script>
<style lang="less" scoped>
.form-btns {
  padding-bottom: 20px;
}
</style>
